package org.snail.excel.annotation;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.snail.excel.common.ExcelDataFormatter;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by WJ on 2017/12/7.
 */
public class ExcelSheetWriteProcessor {

    private static Logger logger = Logger.getLogger(ExcelSheetWriteProcessor.class);

    //内存中的缓存记录数
    private static int intRowAccess = 100;

    /**
     * 写入List到sheet数据
     * @param sheet
     * @param startRow
     * @param list
     * @return
     */
    public Sheet writeToExcelSheet(Sheet sheet, int startRow, List list) {
        try {
            int j = 0;
            if(null!=list && !list.isEmpty() && null!=sheet) {
                initRowTitle(sheet, startRow, list.get(0));
                for (int i = startRow + 1; j < list.size(); j++, i++) {
                    Row row = sheet.createRow(i);
                    writeToExcelRow(row, list.get(j));

                    if (i % intRowAccess == 0) {
                        if (sheet instanceof SXSSFSheet)
                            ((SXSSFSheet) sheet).flushRows();
                    }
                }
            }
        } catch (IOException e) {
            logger.error(e.getStackTrace(),e);
        }
        return sheet;
    }

    /**
     * 初始化表头
     * @param sheet
     * @param startRow
     * @param obj
     */
    private void initRowTitle(Sheet sheet, int startRow, Object obj) {
        if(null!=sheet && null!=obj) {
            Row row = sheet.createRow(startRow);
            ExcelBean excelBean = obj.getClass().getAnnotation(ExcelBean.class);
            if(excelBean!=null && excelBean.isExcelBean()) {
                Field[] fields = obj.getClass().getDeclaredFields();
                //遍历字段，转换为Bean对象
                for (Field field : fields) {
                    field.setAccessible(true);
                    ExcelColumn excelColumn = field.getAnnotation(ExcelColumn.class);
                    if (excelColumn != null && excelColumn.skip() != true) {
                        Cell cell = row.createCell(excelColumn.position());
                        cell.setCellValue(excelColumn.columnName());
                    }
                }
            }
        }
    }

    /**
     * 把一行数据写入到excel中
     * @param row
     * @param obj
     */
    private void writeToExcelRow(Row row, Object obj) {
        if(null!=obj) try {
            {
                ExcelBean excelBean = obj.getClass().getAnnotation(ExcelBean.class);
                if(excelBean!=null && excelBean.isExcelBean()) {
                    Field[] fields = obj.getClass().getDeclaredFields();
                    //遍历字段，转换为Bean对象
                    for (Field field:fields) {
                        field.setAccessible(true);
                        ExcelColumn excelColumn = field.getAnnotation(ExcelColumn.class);
                        if(excelColumn!=null && excelColumn.skip()!=true) {
                            //1、获取单元格的值
                            if(excelColumn.position()>=0 ) {
                                Cell cell = row.createCell(excelColumn.position());
                                Object value = getValue(field, obj);

                                //2、获取单元格的转换器
                                if(null!=value) {
                                    Class edfCls = excelColumn.dataFormatter();
                                    ExcelDataFormatter excelDataFormatter = null;
                                    if (null != edfCls && !(edfCls instanceof Object)) {
                                        excelDataFormatter = (ExcelDataFormatter) edfCls.newInstance();
                                    }

                                    //有值时，进行转换，给Bean对象设置值
                                    setField2Cell(cell, value, excelDataFormatter);
                                }
                            }
                        }
                    }
                }

            }
        } catch (InstantiationException e) {
            logger.error(e.getStackTrace(),e);
        } catch (IllegalAccessException e) {
            logger.error(e.getStackTrace(),e);
        }
    }

    /**
     * 设置单元格的值
     * @param field
     * @return
     */
    private Object getValue(Field field, Object value){
        Object obj = null;
        try {
            Object name = field.getName();
            Class fieldType = field.getType();
            if(fieldType.equals(int.class)) {
                obj = field.getInt(value);
            } else if(fieldType.equals(float.class)) {
                obj = field.getFloat(value);
            } else if(fieldType.equals(boolean.class)) {
                obj = field.getBoolean(value);
            }  else  {
                obj = field.get(value);
            }
        } catch (IllegalAccessException e) {
            logger.error(e.getStackTrace(),e);
        }
        return  obj;
    }

    /**
     * 设置单元格值
     * @param cell
     * @param value
     * @param excelDataFormatter
     */
    private void setField2Cell(Cell cell, Object value, ExcelDataFormatter excelDataFormatter){
        //1、转换器不为空时，进行数据转换
        if(null != excelDataFormatter) {
            value = excelDataFormatter.translate(null, value);
        }

        cell.setCellValue(value.toString());
    }
}
